package com.catazy.cameralib.ui

import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.catazy.cameralib.R
import com.catazy.cameralib.ext.hide
import com.catazy.cameralib.model.ScannerErrorModel
import com.catazy.cameralib.model.ScannerResults
import com.catazy.cameralib.ui.cameraScreen.CameraScreenFragment
//import id.zelory.compressor.Compressor
//import id.zelory.compressor.constraint.format
//import id.zelory.compressor.constraint.quality
//import id.zelory.compressor.constraint.size
//import id.zelory.compressor.extension
//import id.zelory.compressor.saveBitmap
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

/**
 * 作者: Tao
 * 日期: 2024/3/7
 * 时间: 16:37
 * 描述:
 */
abstract class InternalScanActivity:AppCompatActivity() {

    companion object {
        private val TAG = InternalScanActivity::class.simpleName
        internal const val CAMERA_SCREEN_FRAGMENT_TAG =  "CameraScreenFragmentTag"
        internal const val IMAGE_CROP_FRAGMENT_TAG = "ImageCropFragmentTag"
        internal const val IMAGE_PROCESSING_FRAGMENT_TAG = "ImageProcessingFragmentTag"
        internal const val ORIGINAL_IMAGE_NAME = "original"
        internal const val CROPPED_IMAGE_NAME = "cropped"
        internal const val TRANSFORMED_IMAGE_NAME = "transformed"
        internal const val NOT_INITIALIZED = -1L
    }

    internal lateinit var originalImageFile: File
    internal var croppedImage: Bitmap? = null
    internal var transformedImage: Bitmap? = null
    private var imageQuality: Int = 100
    private var imageSize: Long = NOT_INITIALIZED
    private lateinit var imageType: Bitmap.CompressFormat
    internal var shouldCallOnClose = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        reInitOriginalImageFile()
    }

    internal fun reInitOriginalImageFile() {
//        originalImageFile = File(filesDir, "${ORIGINAL_IMAGE_NAME}.${imageType.extension()}")
//        originalImageFile.delete()
    }

    private fun showCameraScreen() {
        val cameraScreenFragment = CameraScreenFragment.newInstance()
        addFragmentToBackStack(cameraScreenFragment, CAMERA_SCREEN_FRAGMENT_TAG)
    }

    internal fun closeCurrentFragment() {
        supportFragmentManager.popBackStackImmediate()
    }

    private fun addFragmentToBackStack(fragment: Fragment, fragmentTag: String) {
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.zdcContent, fragment, fragmentTag)
        if (supportFragmentManager.findFragmentByTag(fragmentTag) == null) {
            fragmentTransaction.addToBackStack(fragmentTag)
        }
        fragmentTransaction.commit()
    }

    internal fun finalScannerResult() {
        findViewById<FrameLayout>(R.id.zdcContent).hide()
        compressFiles()
    }

    private fun compressFiles() {
        Log.d(TAG, "ZDCcompress starts ${System.currentTimeMillis()}")
//        findViewById<ProgressView>(R.id.zdcProgressView).show()
//        CoroutineScope(Dispatchers.IO).launch {
//            var croppedImageFile: File? = null
//            croppedImage?.let {
//                croppedImageFile = File(filesDir, "${CROPPED_IMAGE_NAME}.${imageType.extension()}")
//                saveBitmap(it, croppedImageFile!!, imageType, imageQuality)
//            }
//
//            var transformedImageFile: File? = null
//            transformedImage?.let {
//                transformedImageFile = File(filesDir, "${TRANSFORMED_IMAGE_NAME}.${imageType.extension()}")
//                saveBitmap(it, transformedImageFile!!, imageType, imageQuality)
//            }
//
//            originalImageFile = Compressor.compress(this@InternalScanActivity, originalImageFile) {
//                quality(imageQuality)
//                if (imageSize != NOT_INITIALIZED) size(imageSize)
//                format(imageType)
//            }
//
//            croppedImageFile = croppedImageFile?.let {
//                Compressor.compress(this@InternalScanActivity, it) {
//                    quality(imageQuality)
//                    if (imageSize != NOT_INITIALIZED) size(imageSize)
//                    format(imageType)
//                }
//            }
//
//            transformedImageFile = transformedImageFile?.let {
//                Compressor.compress(this@InternalScanActivity, it) {
//                    quality(imageQuality)
//                    if (imageSize != NOT_INITIALIZED) size(imageSize)
//                    format(imageType)
//                }
//            }
//
//            val scannerResults = ScannerResults(originalImageFile, croppedImageFile, transformedImageFile)
//            runOnUiThread {
////                findViewById<ProgressView>(R.id.zdcProgressView).hide()
//                shouldCallOnClose = false
//                supportFragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
//                shouldCallOnClose = true
//                onSuccess(scannerResults)
//                Log.d(TAG, "ZDCcompress ends ${System.currentTimeMillis()}")
//            }
//        }
    }

    internal fun addFragmentContentLayoutInternal() {
        val frameLayout = FrameLayout(this)
        frameLayout.id = R.id.zdcContent
        addContentView(
            frameLayout, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        )

//        val progressView = ProgressView(this)
//        progressView.id = R.id.zdcProgressView
//        addContentView(
//            progressView, FrameLayout.LayoutParams(
//                FrameLayout.LayoutParams.MATCH_PARENT,
//                FrameLayout.LayoutParams.MATCH_PARENT
//            )
//        )

//        progressView.hide()

        showCameraScreen()
    }


    abstract fun onError(error: ScannerErrorModel)
    abstract fun onSuccess(scannerResults: ScannerResults)
    abstract fun onClose()
}